package com.hc.controller;

import com.alibaba.excel.EasyExcel;
import com.hc.common.bean.PageBean;
import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.common.utils.*;
import com.hc.common.utils.encode.Base64Util;
import com.hc.domain.User;
import com.hc.ex.GlobalException;
import com.hc.listener.UserExcelListener;
import com.hc.common.oss.AliOSSUtil;
import com.hc.query.SearchVO;
import com.hc.query.UserVO;
import com.hc.res.UserDTO;
import com.hc.service.UserService;
import com.hc.trans.UserTrans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author: hecai
 * @date: 2021/11/10 9:40
 * @description:
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserExcelListener userExcelListener;

    /**
     * 用户列表根据id查看指定用户详情
     */
    @GetMapping("/getById/{id}")
    public ModelAndView getById(@PathVariable Serializable id, ModelAndView mav) {
        User user = userService.selectByPrimaryKey(Long.parseLong(id.toString()));
        System.out.println(user);
        mav.addObject("user", user);
        mav.addObject("title", "用户详情");
        mav.setViewName("user/detail");
        return mav;
    }

    /**
     * 用户信息页面进入   修改用户信息
     */
    @GetMapping("/getInfoById/{id}")
    public ModelAndView getInfoById(@PathVariable Serializable id, ModelAndView mav) {
        User user = userService.selectByPrimaryKey(Long.parseLong(id.toString()));
        System.out.println(user);
        mav.addObject("user", user);
        mav.addObject("title", "修改用户信息");
        mav.setViewName("user/update");
        return mav;
    }

    /**
     * 查看当前登录用户的个人信息
     */
    @GetMapping("/getUserInfo")
    public ModelAndView getUserInfo(HttpSession session, ModelAndView mav) {
        User user = (User) session.getAttribute("loginUser");
        User userPersonal = userService.selectByPrimaryKey(user.getId());
        mav.addObject("user", userPersonal);
        mav.addObject("title", "个人信息");
        mav.setViewName("user/detail");
        return mav;
    }

    /**
     * 修改用户信息后跳转详情页面
     */
    @PostMapping("/updateUserInfo/{id}")
    public ModelAndView updateUser(@PathVariable Long id,User user, ModelAndView mav) {
        user.setId(id);
        int updateNum = userService.updateByPrimaryKeySelective(user);
        if(updateNum!=1){
            throw new GlobalException(500,"修改信息错误！");
        }
        User userDetail = userService.selectByPrimaryKey(id);
        mav.addObject("title", "用户详情");
        mav.addObject("user",userDetail);
        mav.setViewName("/user/detail");
        return mav;
    }

    /**
     * 修改个人信息后跳转个人信息界面
     */
    @GetMapping("/updatePersonalInfo")
    public ModelAndView updatePersonalInfo(User user, HttpSession session, ModelAndView mav) {
        User id = (User) session.getAttribute("loginUser");
        user.setId(id.getId());
        userService.updateByPrimaryKeySelective(user);
        mav.addObject("title", "个人信息");
        mav.setViewName("/user/personal");
        return mav;
    }

    @PostMapping("/addUser")
    public Result addUser(User user) {

        // 1. 查询数据库中是否有该用户名
        User user2 = userService.selectByAccount(user.getAccount());
        // 2. 如果没有，则注册。否则返回重新注册
        if (user2 == null) {
            // 3. 密码Md5加密
            String md5Password = Md5Util.encode(user.getPassword());
            user.setPassword(md5Password);
            // 注册默认状态为0（正常）
            user.setStatus(0);
            // 4. 添加入数据库
            int i = userService.insert(user);
            if (i > 0) {
                return ResultUtil.success().setMsg("添加成功！");
            }
        }
        return ResultUtil.fail().setMsg("添加失败！");
    }

    /**
     * 修改用户信息
     */

    @PutMapping("/updateById")
    public ModelAndView updateById(@RequestBody User user, ModelAndView mav) {
        int updateRes = userService.updateByPrimaryKey(user);
        mav.setViewName("user");
        return mav;
    }

    /**
     * 根据id删除用户
     */
    @ResponseBody
    @DeleteMapping("/removeById/{id}")
    public Result removeById(@PathVariable("id") Long[] id) {
        //删除成功的数量
        int deleteRes = 0;
        //遍历需要删除的用户id数组
        for (int i = 0; i < id.length; i++) {
            //成功删除一次，成功数量加1
            deleteRes += userService.deleteByPrimaryKey(id[i]);
        }
        //删除成功的个数和需要删除的个数相同，则删除成功
        if (deleteRes == id.length) {
            return ResultUtil.success().setMsg("删除成功");
        } else {
            return ResultUtil.fail().setMsg("删除失败");
        }
    }

    /**
     * 修改头像
     */
    @ResponseBody
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam("avatar") MultipartFile multipartFile,
                            HttpSession session,   Long id) {
        String avatarUrl = null;
        try {
            avatarUrl = AliOSSUtil.upload(multipartFile);
        } catch (IOException e) {
            throw new GlobalException(408, "图片上传到图片服务器出错");
        }
        User user = User.builder()
                .id(id)
                .avatar(avatarUrl)
                .build();

        userService.updateByPrimaryKeySelective(user);

        User loginUser = userService.selectByPrimaryKey(id);

        session.setAttribute("loginUser",loginUser);
        return ResultUtil.success().setMsg(avatarUrl);
    }

    /**
     * 修改密码
     */
    @GetMapping("/updatePwd")
    public ModelAndView updatePwd(ModelAndView mav) {
        mav.addObject("title", "修改密码");
        mav.setViewName("user/changePwd");
        return mav;
    }

    /**
     * 修改用户密码
     *
     * @param newPwd  新密码
     * @param oldPwd  旧密码
     * @param session 获取当前用户
     * @return 返回结果信息
     */
    @ResponseBody
    @PostMapping("/updatePwdById/{oldPwd}/{newPwd}")
    public Result updatePwdById(@PathVariable String newPwd,
                                @PathVariable String oldPwd,
                                HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        String pwd = Base64Util.encode(oldPwd);
        // 获取ID进行修改密码
        if (pwd.equals(user.getPassword())) {
            user = User.builder()
                    .id(user.getId())
                    .password(Base64Util.encode(newPwd))
                    .build();
            int updateRes = userService.updateByPrimaryKeySelective(user);
            session.invalidate();
            return ResultUtil.success().setMsg("修改密码成功");
        } else {
            return ResultUtil.fail().setMsg("旧密码输入不正确");
        }
    }

    /**
     * 根据查询条件查询用户信息
     */
    @GetMapping("/getUserByCondition/{pageNum}/{pageSize}")
    public ModelAndView getUserByCondition(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize,
            SearchVO searchVO,
            ModelAndView mav,
            String s) {
        UserVO userVO = new UserVO();
        if(!("4".equals(s))){
            userVO.setStatus(s);
        }

        ControllerUtil.initParam(userVO, searchVO);

        PageBean<User> userPageBean = userService.selectPageByCondition(pageNum, pageSize, userVO);
        //转换
        PageBean<UserDTO> userDTOPageBean = UserTrans.MAPPER.user2UserBO(userPageBean);

        userDTOPageBean.setUrl("user/getUserByCondition");
        mav.addObject("pageBean", userDTOPageBean);
        //返回查询条件
        mav.addObject("searchValue", searchVO.getSearchValue());
        mav.addObject("searchKey", searchVO.getSearchKey());
        mav.addObject("status",s);
        mav.addObject("title", "用户列表");
        mav.setViewName("user/list");
        return mav;
    }
    /**
     * 禁用用户页面
     */
    @GetMapping("/active/{pageNum}/{pageSize}")
    public ModelAndView toBatchActive(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize,
            SearchVO searchVO,
            ModelAndView mav) {
        UserVO userVO = new UserVO();
        ControllerUtil.initParam(userVO, searchVO);

        PageBean<User> userPageBean = userService.selectPageByConditionAnother(pageNum, pageSize, userVO);
        //转换
        PageBean<UserDTO> userDTOPageBean = UserTrans.MAPPER.user2UserBO(userPageBean);

        userDTOPageBean.setUrl("user/getUserByCondition");
        mav.addObject("pageBean", userDTOPageBean);
        //返回查询条件
        mav.addObject("searchValue", searchVO.getSearchValue());
        mav.addObject("title", "启用用户");
        mav.setViewName("/user/active");
        return mav;
    }

    /**
     * 已删除用户页面
     */
    @GetMapping("/toDelete/{pageNum}/{pageSize}")
    public ModelAndView toDelete(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize,
            SearchVO searchVO,
            ModelAndView mav) {
        UserVO userVO = new UserVO();
        ControllerUtil.initParam(userVO, searchVO);

        PageBean<User> userPageBean = userService.selectPageHasDelete(pageNum, pageSize, userVO);
        //转换
        PageBean<UserDTO> userDTOPageBean = UserTrans.MAPPER.user2UserBO(userPageBean);

        userDTOPageBean.setUrl("user/getUserByCondition");
        mav.addObject("pageBean", userDTOPageBean);
        //返回查询条件
        mav.addObject("searchValue", searchVO.getSearchValue());
        mav.addObject("title", "已删除用户");
        mav.setViewName("/user/deleteList");
        return mav;
    }

    /**
     * 批量启用用户
     */
    @ResponseBody
    @PostMapping("/activeById/{id}")
    public Result activeById(@PathVariable("id") Long[] id, ModelAndView mav) {
        //启用成功的数量
        int avctiveRes = 0;
        //遍历需要启用的用户id数组
        for (int i = 0; i < id.length; i++) {
            //成功启用一次，成功数量加1
            avctiveRes += userService.activeByPrimaryKey(id[i]);
        }
        //成功的个数和需要启用的个数相同，则启用成功
        if (avctiveRes == id.length) {
            return ResultUtil.success().setMsg("启用成功");
        } else {
            return ResultUtil.fail().setMsg("启用失败");
        }
    }
    /**
     * 批量禁用用户
     */
    @ResponseBody
    @PostMapping("/disabledById/{id}")
    public Result disabledById(@PathVariable("id") Long[] id, ModelAndView mav) {
        //禁用成功的数量
        int disabledRes = 0;
        //遍历需要禁用的用户id数组
        for (int i = 0; i < id.length; i++) {
            //成功禁用一次，成功数量加1
            disabledRes += userService.disabledByPrimaryKey(id[i]);
        }
        //成功的个数和需要禁用的个数相同，则启用成功
        if (disabledRes == id.length) {
            return ResultUtil.success().setMsg("禁用成功");
        } else {
            return ResultUtil.fail().setMsg("禁用失败");
        }
    }



    /**
     * 新增单个用户
     */
    @GetMapping("/insertUser")
    public Result insertUser( @RequestBody User user) {
        User user1 = userService.selectByAccount(user.getAccount());
        int insertRes = 0;
        if (user1==null){
            insertRes = userService.insert(user);
        }
        if (insertRes==0){
            return ResultUtil.success().setMsg("添加成功");
        }
        return ResultUtil.fail().setMsg("添加失败");
    }

    /**
     * 注销
     */
    @GetMapping("/logOut")
    public String logOut(HttpSession session){
        session.invalidate();
        return "redirect:/projshow/login";
    }

    @ResponseBody
    @PostMapping("/registUsers")
    public Result registUsers(@RequestParam("xlsxPath") String xlsxPath){
        xlsxPath = xlsxPath.replace("\\","\\\\");
        System.out.println(xlsxPath);
        EasyExcel.read(xlsxPath, User.class, userExcelListener)
                .sheet()
                .doRead();
        return ResultUtil.success().setMsg("添加成功！");
    }

}